<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>活动列表</title>
  <!--  <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap/4.5.2/css/bootstrap.min.css">-->
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <link rel="stylesheet" href="./css/base.css">
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f2f2f2;
    }
    .activity-list {
      padding:0 30px;
    }
    #activities{
      height: calc(100vh - 134px);
      overflow-y: auto;
      padding-right: 10px;
    }
    .activity-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #f7f7f7;
      padding: 24px;
      border-radius: 4px;
      overflow: hidden;
      margin-bottom: 10px;
      border-radius: 8px;
      padding-bottom: 12px;
    }
    .activity-info{
      width: calc(100% - 220px); /* 宽度减少100px，给删除按钮留出空间 */
    }
    .activity-info h4{
      width: 100%;
      font-weight: 600;
      font-size: 15px;
      color: #000000;
      margin-bottom: 4px;
    }
    .activity-info p{
      font-weight: 400;
      font-size: 14px;
      color: #666666;
      margin: 0;
      line-height: 28px;
    }
    .active a{
      font-weight: 400;
      font-size: 15px;
      color: red;
      margin-bottom: 0;
      display: block;
      width: 250px;
    }
    .inactive a{
      font-weight: 400;
      font-size: 15px;
      color: gray;
      margin-bottom: 0;
      display: block;
      width: 250px;
    }
    /* 新增删除按钮样式 */
    .delete-btn {
      border: none;
      background-color: #dc3545;
      color: white;
      padding: 4px 12px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-left: 15px;
    }
    .delete-btn:hover {
      background-color: #c82333; /*  hover时加深颜色 */
    }
    .pagination {
      display: flex;
      justify-content: flex-end;
      margin-top: 18px;
      padding-right: 16px;
    }
    .pagination button {
      margin: 0 5px;
      border-radius: 5px;
      border: 1px solid #007bff;
      background-color: #fff;
      padding: 0px 8px;
      cursor: pointer;
      font-size: 13px;
    }
    .pagination span{
      margin: 0 10px;
      font-size: 14px;
    }
    .pagination input{
      width: 80px;
      text-align: center;
    }
    .activity-list h2 {
      font-weight: 600;
      font-size: 18px;
      color: #000000;
      height: 70px;
      display: flex;
      align-items: center;
      margin-bottom: 0;
    }
  </style>
</head>
<body style="background-color: white">
<div class="activity-list">
  <h2>活动列表</h2>
  <div id="activities">
    <!-- 活动列表将动态插入这里 -->
  </div>
  <div class="pagination">
    <button class="btn-outline-primary" onclick="fetchActivities(1)">首页</button>
    <button class="btn-outline-primary" onclick="previousPage()">上一页</button>
    <span>第 <input type="number" id="pageInput" min="1" value="1" /> 页</span>
    <button class="btn-outline-primary" onclick="nextPage()">下一页</button>
    <button class="btn-outline-primary" onclick="fetchActivities(totalPages)">尾页</button>
  </div>
</div>
<script src="./js/jquery.min.js"></script>
<script src="./js/toastr.min.js"></script>
<script>
  var currentPage = 1;
  var pageSize = 10;
  var totalPages;
  var userToken = localStorage.getItem("user_token");

  // 发送AJAX请求获取活动列表
  function fetchActivities(page) {
    if (page < 1) {
      page = 1;
    }
    currentPage = page;
    var dataToSend = {
      currentPage: currentPage,
      pageSize: pageSize
    };
    $.ajax({
      url: '/activity/find-list',
        type: 'GET',
        data: dataToSend,
        dataType: 'json',
        headers: {
          "user_token": userToken
        },
        success: function(result) {
          if (result.code != 200) {
              alert("查询活动列表失败！" + result.msg);
          } else {
              var activities = result.data.records;
              var activitiesHtml = '';
              var listContainer = document.getElementById('activities');
              listContainer.innerHTML = '';
              activities.forEach(function(activity) {
                var url = 'draw.html?activityName='+ encodeURIComponent(activity.activityName)
                        +'&activityId=' + encodeURIComponent(activity.activityId)
                        +'&valid=' + encodeURIComponent(activity.valid);
                var linkTextActive = `<a href="${url}" target="_blank">活动进行中，去抽奖</a>`;
                var linkTextInactive = `<a href="${url}" target="_blank">活动已完成，查看中奖名单</a>`;
                var validClass = activity.valid ? 'active' : 'inactive';
                var link = activity.valid ? linkTextActive : linkTextInactive;
                // 新增删除按钮，绑定删除事件并传入活动ID
                activitiesHtml += `
                    <div class="activity-item">
                      <div class="activity-info">
                        <h4>${activity.activityName}</h4>
                        <p>${activity.description}</p>
                      </div>
                      <div style="display: flex; align-items: center;"> <!-- 弹性布局使链接和删除按钮横向排列 -->
                        <div class="${validClass}">
                          <p>${link}</p>
                        </div>
                        <button class="delete-btn" onclick="deleteActivity(${activity.activityId})">删除活动</button>
                      </div>
                    </div>
                  `;
              });
              $('#activities').html(activitiesHtml);
              totalPages = Math.ceil(result.data.total / pageSize);
              $('#pageInput').val(currentPage);
            }
        },
      error:function(err){
        console.log(err);
        if(err!=null && err.status==401){
          alert("用户未登录, 即将跳转到登录页!");
          window.location.href = "/blogin.html";
          window.parent.location.href = "/blogin.html";
        }
      }
    });
  }

  // 新增：删除活动函数
  function deleteActivity(activityId) {
    // 确认删除弹窗，防止误操作
    if (!confirm("确定要删除该活动吗？删除后不可恢复！")) {
      return; // 取消删除，直接返回
    }

    // 发送删除请求（对应后端@DeleteMapping("/deleteActivity")接口）
    $.ajax({
      url: '/deleteActivity',
      type: 'DELETE', // 对应后端Delete请求方式
      data: { id: activityId }, // 传递活动ID，参数名与后端@RequestParam Long id一致
      dataType: 'json',
      headers: {
        "user_token": userToken // 携带登录令牌，保证接口权限
      },
      success: function(result) {
        // 假设后端返回true表示删除成功（与后端public boolean deleteActivity返回值对应）
        if (result) {
          alert("活动删除成功！");
          fetchActivities(currentPage); // 重新加载当前页列表，更新删除后的结果
        } else {
          alert("活动删除失败，请稍后重试！");
        }
      },
      error: function(err) {
        console.log("删除活动请求失败：", err);
        if (err.status == 401) {
          alert("用户未登录，无法执行删除操作！即将跳转到登录页！");
          window.location.href = "/blogin.html";
          window.parent.location.href = "/blogin.html";
        } else {
          alert("删除请求异常，错误信息：" + (err.responseText || "网络错误"));
        }
      }
    });
  }

  function previousPage() {
    if (currentPage > 1) {
      fetchActivities(currentPage - 1);
    } else {
      alert("已经是第一页");
    }
  }

  function nextPage() {
    if (currentPage < totalPages) {
      fetchActivities(currentPage + 1);
    } else {
      alert("已经是最后一页");
    }
  }

  $(document).ready(function() {
    fetchActivities(1);
  });

  $('#pageInput').on('keypress', function(e) {
    if (e.key === 'Enter') {
      var page = parseInt(this.value);
      if(page > totalPages){
        page = totalPages
        $('#pageInput').val(totalPages);
      }
      if (!isNaN(page) && page >= 1 && page <= totalPages) {
        fetchActivities(page);
      }
    }
  });
</script>
</body>
</html>